const Router = require('@koa/router')
const router = new Router()
const { userLogin, userFind, userRegister } = require('../controllers/index.js')
const { escape } = require('../lib/security.js')


const { sign, verify, refreshVerify } = require('../lib/jwt.js')

router.prefix('/user')
router.post('/login', async (ctx) => {
    // 1. 获取请求体中的账号密码
    // post 请求携带的参数都在请求体中  
    let { username, password } = ctx.request.body
    // console.log(username,password)
    //2. 检查账号密码是否合法
    //3. 去数据库查询账号密码是否正确
    //注册时已经转译了
    username = escape(username)
    password = escape(password)
    //4. 登录成功，返回token
    try {
        const res = await userLogin(username, password)
        if (res.length) {//找到了有数据
            let data = {
                id: res[0].id,
                username: res[0].username,
                nikcname: res[0].nikcname,
                create_time: res[0].create_time,
            }
            const access_token = sign(data, '1h')//短token
            const refresh_token = sign(data, '7d')//长token
            ctx.body = {
                code: '1',
                msg: '登录成功',
                data: data,
                access_token: access_token,
                refresh_token: refresh_token,
            }
        } else {//逻辑性错误
            ctx.body = {
                code: '0',
                msg: '登录失败',
            }
        }
    } catch (error) {//程序性错误
        ctx.body = {
            code: '-1',
            msg: '服务器异常',
            data: error
        }
    }
})

// 刷新token
router.post('/refresh', async (ctx) => {
    const { refresh_token } = ctx.request.body
    //校验refresh_token是否有效
    const decoded = refreshVerify(refresh_token)
    if (decoded.id) {
        //创建新的长短token
        const data = {
            id: decoded.id,
            username: decoded.username,
            nikcname: decoded.nikcname,
            create_time: decoded.create_time,
        }
        const access_token = sign(data, '1h')//短token
        const refresh_token = sign(data, '7d')//长token
        ctx.body = {
            code: '1',
            msg: '刷新成功',
            access_token: access_token,
            refresh_token: refresh_token,
        }
    } else { //长token都过期了                                                                                   
        ctx.status = 416
        ctx.body = {
            code: '0',
            msg: '登录失效'
        }

    }

})
// 注册接口
router.post('/register', async (ctx) => {
    let { username, password, nickname } = ctx.request.body
    if (!username || !password || !nickname) {
        ctx.body = {
            code: '0',
            msg: '请填写完整信息',
            data: {}
        }
        return
    }
    // 转译标签，防止sql注入
    username = escape(username)
    password = escape(password)
    nickname = escape(nickname)

    try {
        const res = await userFind(username)
        if (res.length) {
            ctx.body = {
                code: '0',
                msg: '账号已存在',
                data: {}
            }
            return
        }
        //数据库写入
        const result = await userRegister({ username, password, nickname, create_time: Date.now() })
        if (result.affectedRows) {
            ctx.body = {
                code: '1',
                msg: '注册成功',
                data: {}
            }
        } else {
            ctx.body = {
                code: '0',
                msg: '注册失败',
                data: {}
            }

        }
    } catch (error) {
        ctx.body = {
            code: '-1',
            msg: '服务器异常',
            data: error
        }


    }





})

router.get('/test', verify(), async (ctx) => {
    ctx.body = {
        code: '1',
        msg: '测试成功'
    }
})


module.exports = router
